#include "service/include/swei_cmd.h"
#include "service/include/swei_downlink.h"
#include "comm/co_heartbeat.h"
#include "aadl/public.h"

static DLCMD_RET_TYPE_ENUM tbox_ble_handler(DOWN_LINK_CMD_ENUM cmd_id, uint16_t cmd_opcode, const unsigned char * p_data, uint32_t data_len);

DOWN_LINK_CMD_ENUM ble_tbl[] = {
    DOWN_LINK_CMD_BLE_DISTANCE,               // 蓝牙感应距离设置 0 近 / 1 标准 / 2 远
    DOWN_LINK_CMD_BLE_INSEN_UNLOCK,           // 蓝牙无感解锁 0 关 / 1 开    
};

static ble_cfg_t ble_cfg = {
    .ble_detect_level = 1,
    .ble_inductiveunlock_enable = 0,
};

void swei_ble_init(void)
{
    for (int i = 0; i < ARRAY_COUNT(ble_tbl); i++)
    {
        swei_downlink_cmd_register(ble_tbl[i], tbox_ble_handler);
    }
}

static DLCMD_RET_TYPE_ENUM tbox_ble_handler(DOWN_LINK_CMD_ENUM cmd_id, uint16_t cmd_opcode, const unsigned char * p_data, uint32_t data_len)
{
    #if 0
    if (p_data == NULL || is_ebike_mcu_off())
    #else 
    if (p_data == NULL)      
    #endif
        return DLCMD_RET_ERROR;

    switch(cmd_id)
    {
        case DOWN_LINK_CMD_BLE_DISTANCE:
            memcpy(&ble_cfg.ble_detect_level, p_data, data_len);
            co_ble_cfg(&ble_cfg, 0);  
            break;

        case DOWN_LINK_CMD_BLE_INSEN_UNLOCK:
            memcpy(&ble_cfg.ble_inductiveunlock_enable, p_data, data_len);
            co_ble_cfg(&ble_cfg, 1);
            break;

        default:
            break;
    }

    swei_netProtocol_ack_downlink_cmd(cmd_id, CMD_SUCCESS, true);
    return DLCMD_RET_CONTINUE;
}